from django.db import connection

from app.model.cs_goods_barcodes import CsGoodsBarcodes
from libs.db import DB


def get_shop_goods_id_by_barcode(shop_id, barcode):
    goods_id = 0
    try:
        db_goods = CsGoodsBarcodes.objects.filter(shop_id=shop_id, barcode=barcode).values('goods_id').get()
        goods_id = db_goods.get('goods_id', 0)
    except CsGoodsBarcodes.DoesNotExist:
        pass
    if goods_id == 0:
        db = DB('table_goods')
        db_goods = db.one(['id'], {'shoper_id': shop_id, 'barcode': barcode})
        goods_id = db_goods.get('id', 0)
    return goods_id


def save_shop_goods_barcode(shop_id, goods_id, barcode):
    record_id = 0
    try:
        goods_barcode = CsGoodsBarcodes()
        goods_barcode.shop_id = shop_id
        goods_barcode.goods_id = goods_id
        goods_barcode.barcode = barcode
        goods_barcode.save()
        record_id = goods_barcode.id
    except Exception as e:
        print(e)
    try:
        db = DB('table_goods')
        db.update({'barcode': barcode}, {'id': goods_id})
    except Exception as e:
        print(e)
    return record_id


def save_barcode_archives(barcode_data):
    try:
        db_barcode = barcode_data.get('barcode')
        if len(db_barcode) == 13:
            flag = db_barcode[0:2]
            barcode_data.update({'flag': flag})
            db = DB('cs_barcodes')
            db.insert(barcode_data)
    except Exception as e:
        print('add barcode err', e)


def get_barcode_from_archives(barcode):
    common_data = {}
    try:
        with connection.cursor() as cursor:
            db = DB('cs_barcodes', conn=cursor)
            common_data = db.one(['barcode', 'goods_name', ('price', 'usdt_price'), 'unit'], {'barcode': barcode})
            db = DB('table_warehouse_pictures', conn=cursor)
            img1 = db.val('pic_url', {'good_barcode': barcode, 'type': 1})
            if type(img1) is str:
                common_data.update({'goods_img': img1})
            img2 = db.val('pic_url', {'good_barcode': barcode, 'type': 2})
            if type(img2) is str:
                common_data.update({'content_img': img2})
    except Exception as e:
        print('add barcode err', e)
    return common_data
